package com.daidai.activitys

import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.viewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.RecyclerView
import com.daidai.base.BaseActivity
import com.daidai.spinner.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

data class ItemData(val name:String,val pkgName:String,val iconRes:Drawable)


class Holder(rootView:View,
            val ivIcon:ImageView,
             val tvName:TextView,
             val tvPkg:TextView
             ): RecyclerView.ViewHolder(rootView)

class MyAdpter( val lst:List<ItemData>) : RecyclerView.Adapter<Holder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item,parent,false)
        return Holder(view,
            view.findViewById(R.id.ivIcon),
            view.findViewById(R.id.tvName),
            view.findViewById(R.id.tvPkg)
            )
    }

    override fun onBindViewHolder(holder: Holder, position: Int) {
        val data = lst[position]
        holder.ivIcon.setImageDrawable(data.iconRes)
        holder.tvName.text = data.name
        holder.tvPkg.text = data.pkgName
    }

    override fun getItemCount(): Int {
        return lst.size
    }

}

class AppViewModel:ViewModel(){
    fun getLst(packageManager:PackageManager,callback: (ArrayList<ItemData>)->Unit){
        viewModelScope.launch {
            val lst = ArrayList<ItemData>()
            val defer = async(Dispatchers.Default){
                val packInfoLst = packageManager.getInstalledPackages(0)
                for (pg in packInfoLst){
                    val info = packageManager.getApplicationInfo(pg.packageName,PackageManager.GET_META_DATA)
                    val name = packageManager.getApplicationLabel(info)
                    val icon = packageManager.getApplicationIcon(pg.packageName)
                    lst.add(ItemData(name.toString(),pg.packageName,icon))
                }
            }
            defer.await()
            callback(lst)
        }
    }
}

class ViewPackageActivity : BaseActivity() {

    lateinit var rvLst:RecyclerView

    val model:AppViewModel by viewModels()

    override fun getContentViewResId(): Int = R.layout.activity_package

    override fun initView() {
        rvLst = findViewById(R.id.rvLst)
    }

    override fun initData() {
        model.getLst(packageManager){lst->
            rvLst.adapter = MyAdpter(lst)
        }
    }
}